package com.hzspace.jar;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * 线程池
 *
 * @Version 1.0
 * @Author hz
 * @Date 2021/1/20 17:20
 */
@Slf4j
@Configuration
public class MollyBoxThreadPool {

    @Value("${core.pool.size:10}")
    private Integer corePoolSize;

    @Value("${maximum.pool.size:20}")
    private Integer maximumPoolSize;

    @Value("${keep.alive.time:30}")
    private Integer keepAliveTime;

    @Value("${blocking.queue.capacity:100}")
    private Integer blockingQueueCapacity;

    @Value("${thread.name.prefix:MollyBox}")
    private String threadNamePrefix;

    private ExecutorService executorService;

    @PostConstruct
    private void init() {
        if (executorService == null) {
            synchronized (this) {
                executorService = new ThreadPoolExecutor(
                        corePoolSize,
                        maximumPoolSize,
                        keepAliveTime,
                        TimeUnit.SECONDS,
                        new LinkedBlockingQueue<>(blockingQueueCapacity),
                        r -> {
                            Thread t = new Thread(r);
                            t.setDaemon(true);
                            t.setName(threadNamePrefix + "-Thread-" + t.getId());
                            return t;
                        },
                        new ThreadPoolExecutor.DiscardPolicy());
                log.info("初始化线程池====》核心线程数:{}, 最大线程数:{}", corePoolSize, maximumPoolSize);
            }
        }

    }

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public void submit(Runnable task) {
        executorService.submit(task);
    }

    public Future<?> submit(Callable task) {
        return executorService.submit(task);
    }

    public void shutDown() {
        executorService.shutdown();
    }

    public void shutDownNow() {
        executorService.shutdownNow();
    }

}
